<template>
<div class="row">
  <vs-aside :show.sync="showSetting" placement="left" :header="this.$t('common.params')" :width="300">
    <form class="form"> 
      <div class="form-group">
        <label class="control-label">{{$t("webapp.encoder")}}</label>
        <input type="text" class="form-control input-sm" v-model="ipaddr">
      </div>
      <div class="form-group">
        <label class="control-label">{{$t("video.resolution")}}</label>
        <select class="form-control input-sm" v-model="resolution">
          <option v-for="option in resolutionOptions" :value="option.value">{{option.text}}</option>
        </select>
      </div> 
      <div class="form-group">
        <label class="control-label">{{$t("video.quality")}}</label>
        <select class="form-control input-sm" v-model="stream">
          <option v-for="option in qualityOptions" :value="option.value">{{option.text}}</option>
        </select>
      </div> 
      <button class="btn btn-sm btn-default pull-right" @click.prevent="onRefresh">
        <span class="glyphicon glyphicon-refresh"></span> {{$t("common.refresh")}}
      </button>                         
    </form>       
  </vs-aside>
  <div class="my-vid-marker">
    <canvas class="vmarker" v-el:video></canvas>
    <canvas class="vmarker" v-el:board></canvas>
  </div>
  <div class="col-md-12">
    <div class="toolbar">
      <ul style="list-style: none; display: inline">
        <li style="margin-left: 0;" class="draw-icon" @click.prevent="onShowSetting" v-show="enableSetting"><i class="fa fa-cog"></i></li>
        <li class="draw-icon" @click.prevent="onClearPage"><i class="fa fa-file-o"></i></li>
        <li v-for="option in toolOptions" :class="toolClass(option.class, $index)" @click="onChangeTool($index)">{{{option.showHtml}}}</li>
      </ul>

      <ul class="color-pallet">
        <li v-for="option in colorOptions" :style="{'background-color': option.color}" :class="{active: activeColorIndex === $index}" @click.prevent="onChangeColor($index)"></li>
      </ul>
    </div>      
  </div> 
</div>
</template>

<script>
import _ from 'lodash'
import locales from './locales.js'
import {http} from 'share/common/api.js'
import {getQueryStringArgs, checkValidIp} from 'libs/utils.js'
import toast from 'libs/toast.js'
import WSAvcPlayer from 'libs/wsAvc.js'
var paper = require('external/js/paper-full.min.js')

export default {
  locales,
  data () {
    return {
      enableSetting: false,
      showSetting: false,
      ipaddr: '',
      stream: 'preview',
      resolution: '1920x1080',
      resolutionOptions: [{
        value: '1920x1080',
        text: '1080p'
      }, {
        value: '1280x720',
        text: '720p'
      }, {
        value: '1440x900',
        text: '1440x900'
      }, {
        value: '1024x768',
        text: '1024x768'
      }],
      qualityOptions: [{
        value: 'preview',
        text: this.$t("video.sd")
      }, {
        value: 'sub',
        text: this.$t("video.hd")
      }],
      activeColorIndex: 0,
      colorOptions: [{
        color: "#FF0000"
      }, {
        color: "#990000"
      }, {
        color: "#00FF00"
      }, {
        color: "#009900"
      }, {
        color: "#0000FF"
      }, {
        color: "#000099"
      }, {
        color: "#FFFF00"
      }, {
        color: "#FF9900"
      }, {
        color: "#99FF00"
      }, {
        color: "#FF00FF"
      }, {
        color: "#FF0099"
      }, {
        color: "#9900FF"
      }, {
        color: "#00FFFF"
      }, {
        color: "#0099FF"
      }, {
        color: "#00FF99"
      }],
      activeToolIndex: 0,
      toolOptions: [{
        tool: "pencil",
        class: "draw-icon pencil-icon",
        showHtml: '<i class="fa fa-pencil"></i>'
      }, {
        tool: "line",
        class: "draw-icon text-icon",
        showHtml: '线'
      }, {
        tool: "rect",
        class: "draw-icon text-icon",
        showHtml: '方'
      }, {
        tool: "ellipse",
        class: "draw-icon text-icon",
        showHtml: '圆'
      }, {
        tool: "eraser",
        class: "draw-icon eraser-icon",
        showHtml: '<i class="fa fa-eraser"></i>'
      }],
      toolPenSize: 0,
      toolColor: "",
      canvasWidth: 1920,
      canvasHeight: 1080
    }
  },
  computed: {
    wsHost () {
      return `ws://${this.ipaddr}:7080`
    },
    srcWidth () {
      return parseInt(this.resolution.split('x')[0])
    },
    srcHeight () {
      return parseInt(this.resolution.split('x')[1])
    },
    xScale () {
      return this.srcWidth / this.canvasWidth
    },
    yScale () {
      return this.srcHeight / this.canvasHeight
    },
    penScale () {
      return this.xScale * this.yScale
    }
  },
  methods: {
    toolClass (baseClass, index) {
      if (this.activeToolIndex === index) {
        return `${baseClass} active`
      } else {
        return baseClass
      }
    },
    onShowSetting () {
      this.showSetting = true
    },
    onChangeColor (index) {
      this.activeColorIndex = index
      this.toolColor = this.getCurrColor()
    },
    getCurrColor () {
      return this.colorOptions[this.activeColorIndex].color
    },
    doClearPage () {
      paper.project.clear()
      paper.view.draw()
    },
    onClearPage () {
      this.devClearTrack()
      this.doClearPage()
    },
    initTool () {
      var tool = this.getCurrTool()
      if (tool === 'pencil' 
        || tool === 'line' 
        || tool === 'rect' 
        || tool === 'ellipse') {
        this.toolPenSize = 6 / this.penScale
        this.toolColor = this.getCurrColor()
      }
      if (tool === 'eraser') {
        this.toolPenSize = 30 / this.penScale
        this.toolColor = "#ffffff"
      }

      console.log('pensize:' + this.toolPenSize)
    },
    onChangeTool (index) {
      this.activeToolIndex = index
      this.initTool()
    },
    getCurrTool () {
      return this.toolOptions[this.activeToolIndex].tool
    },
    initCfgOfPath () {
      var path = this.path

      if (path) {
        path.strokeColor = this.toolColor
        path.strokeWidth = this.toolPenSize
      }
    },
    onMouseDown (e) {
      var tool = this.getCurrTool()

      if (tool === 'pencil' 
        || tool === 'eraser') {
        this.path = new paper.Path()
      } else if (tool === 'line') {
        this.path = new paper.Path.Line(e.point, e.point)
      } else if (tool === 'rect') {
        this.path = new paper.Path.Rectangle(e.point, e.point)
      } else if (tool === 'ellipse') {
        this.path = new paper.Path.Ellipse(new paper.Rectangle(e.point, e.point))
      }

      this.initCfgOfPath()
    },
    onMouseDrag (e) {
      var tool = this.getCurrTool()

      if (tool === 'pencil' 
        || tool === 'eraser') {
        this.path.add(e.point)
      } else if (tool === 'line') {
        this.path.lastSegment.point = e.point
      } else if (tool === 'rect') {
        this.path.removeSegments()
        var points = [e.downPoint, new paper.Point(e.point.x, e.downPoint.y), e.point, new paper.Point(e.downPoint.x, e.point.y)]
        this.path.addSegments(points)
      } else if (tool === 'ellipse') {
        this.path.remove()
        this.path = new paper.Path.Ellipse(new paper.Rectangle(e.downPoint, e.point))
        this.initCfgOfPath()
      }

      if (this.timer) {
        clearTimeout(this.timer)
      }
    },
    onMouseUp (e) {
      this.devSyncTrack()
      this.timer = setTimeout(function() {
        this.doClearPage()
        this.timer = null
      }.bind(this), 2000)       
    },
    makeSrcPen (val) {
      return Math.round(val * this.penScale)
    },
    makeSrcX (val) {
      return Math.round(val * this.xScale)
    },
    makeSrcY (val) {
      return Math.round(val * this.yScale)
    },
    getCurrPath () {
      return _.map(this.path.segments, function(item) {
        return {
          x: this.makeSrcX(item.point.x),
          y: this.makeSrcY(item.point.y)
        }
      }.bind(this))
    },
    getCurrLine () {
      var segments = this.path.segments
      return {
        x1: this.makeSrcX(segments[0].point.x),
        y1: this.makeSrcY(segments[0].point.y),
        x2: this.makeSrcX(segments[1].point.x),
        y2: this.makeSrcY(segments[1].point.y)
      }
    },
    getCurrRect () {
      var bounds = this.path.bounds
      return {
        left: this.makeSrcX(bounds.point.x),
        top: this.makeSrcY(bounds.point.y),
        right: this.makeSrcX(bounds.point.x + bounds.width),
        bottom: this.makeSrcY(bounds.point.y + bounds.height)
      }
    },
    sendWsCmd (cmd) {
      if (this.ws) {
        this.ws.send(JSON.stringify(cmd))
      }
    },
    devSyncTrack () {
      var paramlist = {}
      var cmd = {
        action: "",
        paramlist: paramlist
      }
      var tool = this.getCurrTool()

      if (tool === 'pencil' 
        || tool === 'line'
        || tool === 'rect' 
        || tool === 'ellipse') {
        cmd.action = 'addTrack'
        paramlist.color = this.toolColor
        paramlist.lineSize = this.makeSrcPen(this.toolPenSize)
        if (tool === 'pencil') {
          paramlist.path = this.getCurrPath()
        } else if (tool === 'line') {
          paramlist.line = this.getCurrLine()
        } else if (tool === 'rect') {
          paramlist.rect = this.getCurrRect()
        } else if (tool === 'ellipse') {
          paramlist.ellipse = this.getCurrRect()
        }
      } else if (tool === 'eraser') {
        cmd.action = 'eraseTrack';
        paramlist.eraseWidth = this.makeSrcPen(this.toolPenSize)
        paramlist.path = this.getCurrPath()
      } else {
        return
      }

      this.sendWsCmd(cmd)
    },
    devClearTrack () {
      this.sendWsCmd({
        action: "clearTrack",
        paramlist: {}
      })
    },
    vidMarkerInit () {
      let wsUrl = `${this.wsHost}/websocket/stream/${this.stream}`
      var vidmarker = new WSAvcPlayer(this.$els.video, "webgl", 1, 35)
      vidmarker.connect(wsUrl, function(handler) {
        handler.startPlay()
      })
      this.vidmarker = vidmarker

      var canvas = this.$els.board
      paper.setup(canvas)
      var tool = new paper.Tool()
      tool.minDistance = 10
      tool.onMouseDown = this.onMouseDown
      tool.onMouseDrag = this.onMouseDrag
      tool.onMouseUp = this.onMouseUp
    },
    vidMarkerUninit () {
      if (this.vidmarker) {
        this.vidmarker.disconnect()
        this.vidmarker = undefined
      }
    },
    wsMarkerInit () {
      let wsUrl = `${this.wsHost}/websocket/vidmarker`

      var ws = new WebSocket(wsUrl, ['chat'])
      ws.onopen = function(e) {
      }.bind(this)
      ws.onmessage = function(e) {
      }.bind(this)
      ws.onclose = function(e) {
      }.bind(this)
      ws.onerror = function(e) {
      }.bind(this)
      this.ws = ws
    },
    wsMarkerUninit () {
      if (this.ws) {
        this.ws.close()
        this.ws = undefined
      }
    },
    onRefresh () {
      if (!checkValidIp(this.ipaddr)) {
        toast.e(this, this.$t('common.fail'), this.$t('error.invalidAddr'))
        return
      }

      this.showSetting = false

      this.wsMarkerUninit()
      this.vidMarkerUninit()

      this.initTool()
      this.vidMarkerInit()
      this.wsMarkerInit()

      this.canvasWidth = this.$els.board.width
      this.canvasHeight = this.$els.board.height
    },
  },
  ready () {
    let args = getQueryStringArgs()
    if (args) {
      if (args['ddis']) {
        this.ipaddr = JSON.parse(args['ddis']).ipaddr
      }
      if (args['ip']) {
        this.ipaddr = args['ip']
      }
      if (args['stream']) {
        this.stream = args['stream']
      }

      if (this.ipaddr !== '') {
        setTimeout(this.onRefresh, 1000)
      } else {
        this.enableSetting = true
      }
    } else {
      this.enableSetting = true
    }
  }
}
</script>

<style scoped>
.my-vid-marker {
  position: absolute;
  margin: 0; 
  padding: 0;
  width: 100%;
  height: 100%;
}

.vmarker {
  position: absolute;
  height: 100%; 
  width: 100%;
}

.toolbar {
  background: #E6E8EB;
  height: 65px;
  width: 960px;
  margin: 0 auto;
}

.pencil-icon {

}

.eraser-icon {

}

.draw-icon {
  display: inline-block;
  font-size: 30px;
  margin-top: 7px;
  margin-left: 10px;
  color: #4e5d78;
  cursor: pointer;
}

.draw-icon.active {
  color: #009be7;
  border: 2px solid;
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 10px;
}

li.draw-icon.text-icon {
  font-family: '宋体';
}

.color-pallet {
  list-style: none;
  display: inline;
}

.color-pallet li {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 30px;
  padding: 3px;
  margin-left: 6px;
  cursor: pointer;
  border: 4px solid transparent;
  background: transparent;
  border-radius: 22px;
  -moz-border-radius: 22px;
  -webkit-border-radius: 22px;
  -khtml-border-radius: 22px;
}

.color-pallet li.active {
  border: 5px solid #d3d3d3;
  border-radius: 22px;
}
</style>